package com.haiberg.framework.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
 
public class JsonUtil {
	
	/**
	 * 从json字符串中解析出java对象
	 * @author:qiuchen
	 * @createTime:2012-7-8
	 * @param jsonStr json格式字符串
	 * @param clazz java类
	 * @return clazz的实例
	 */
	public static Object parseJavaObject(String jsonStr,Class clazz){
		return JSON.toJavaObject(JSON.parseObject(jsonStr), clazz);
	}
	
	/**
	 * 测试方法
	 * @author:qiuchen
	 * @createTime:2012-7-8
	 * @param args
	 */
	public static void main(String[] args) {
		//0.0加载属性文件(所有json字符串从文件中读取)
		Properties pp = PropertiesUtil.getProperties("d:/properties.properties");
		
		//0.1简单格式的json字符串
		String json1 = pp.getProperty("json1"); 
		System.out.println(json1);
		User user = (User)JsonUtil.parseJavaObject(json1,User.class);
		ReflectionUtil.getFieldValue(user);
		
		
		//0.2数组形式的json字符串
		String json2 = pp.getProperty("json2"); 
		System.out.println(json2);
		JSONArray array = JSONArray.parseArray(json2);
		List<User> userList = new ArrayList<User>();
		for(int i = 0; i < array.size();i++){
			JSONObject jobj = (JSONObject)array.get(i);
			User user2 = JSON.toJavaObject(jobj,User.class);
			userList.add(user2);
		}
		for(User u : userList){
			ReflectionUtil.getFieldValue(u);
		}
		
		//0.3复杂数组形式的json字符串
		String json3 = pp.getProperty("json3");
		System.out.println(json3);
		User user3 = (User)JsonUtil.parseJavaObject(json3, User.class);
		ReflectionUtil.getFieldValue(user3);
		for(Hobby h : user3.getHobbies()){
			ReflectionUtil.getFieldValue(h);
		}
	}
}
class User{
	List<Hobby> hobbies;
	String name;
	int age;
	String sex;
	public List<Hobby> getHobbies() {
		return hobbies;
	}
	public void setHobbies(List<Hobby> hobbies) {
		this.hobbies = hobbies;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
}
class Hobby{
	String name;
	String hYear;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String gethYear() {
		return hYear;
	}
	public void sethYear(String hYear) {
		this.hYear = hYear;
	}
	
}
